/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.core.extend;

import com.inspur.edp.lcm.metadata.api.entity.MetadataCompilerContext;
import com.inspur.edp.lcm.metadata.api.entity.MetadataProject;
import com.inspur.edp.lcm.metadata.api.entity.OperationEnum;
import com.inspur.edp.lcm.metadata.api.service.MetadataProjectService;
import com.inspur.edp.lcm.metadata.common.FileServiceImp;
import com.inspur.edp.lcm.metadata.spi.BeforeCompileAction;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

import java.nio.file.Files;
import java.nio.file.Paths;

public class PackageBeforeCompileActionImpl implements BeforeCompileAction {
    private static PackageBeforeCompileActionImpl instance;
    public static PackageBeforeCompileActionImpl getInstance() {
        if (instance == null) {
            instance = new PackageBeforeCompileActionImpl();
        }
        return instance;
    }

    @Override
    public void validate(MetadataCompilerContext context) {
        // 对编译影响因素进行检测，提前抛出异常。
        if (Files.notExists(Paths.get(context.getProjectPath()))) {
            throw new RuntimeException("检测到工程路径错误：" + context.getProjectPath());
        }
    }

    @Override
    public boolean isSourceFileChanged(MetadataCompilerContext context) {
        MetadataProjectService metadataProjectService = SpringBeanUtils.getBean(MetadataProjectService.class);
        // 检查元数据是否改变
        boolean metadataChanged = metadataProjectService.isMetadataChanged(context.getProjectPath(), OperationEnum.METADATA_PACK);
        // 检查元数据包是否改变
        MetadataProject metadataProjInfo = metadataProjectService.getMetadataProjInfo(context.getProjectPath());
        if (metadataProjInfo == null) {
            throw new RuntimeException("获取工程信息失败：" + context.getProjectPath());
        }
        String mdpkgPath = FileServiceImp.combinePath(metadataProjectService.getProjectBinPath(context.getProjectPath()), metadataProjectService.getMdpkgName(context.getProjectPath()));
        boolean isMdpkgChanges = metadataProjectService.isFileChanged(mdpkgPath, OperationEnum.METADATA_PACK);
        return metadataChanged || isMdpkgChanges;
    }
}
